package com.shenmazong.servertalkadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shenmazong.pojo.TbStudent;
import com.shenmazong.pojo.TbTeacher;
import com.shenmazong.servertalkadmin.mapper.TbTeacherMapper;
import com.shenmazong.servertalkadmin.service.TbTeacherService;
import com.shenmazong.utils.JwtTokenUtils;
import com.shenmazong.utils.ResponseResult;
import com.shenmazong.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TbTeacherServiceImpl implements TbTeacherService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TbTeacherMapper tbTeacherMapper;

    @Override
    public ResponseResult addTeacherUser(String userName, String nickName, Integer subjectId, Long classPrice, Long classFee) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //-- 检查用户是否存在
        TbTeacher teacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>()
                .eq("user_name", userName)
                .last("limit 1"));
        if(teacher != null) {
            result.setFailMessage("教师已存在");
            return result;
        }

        //--1 用户名
        teacher = new TbTeacher();
        teacher.setNickName(nickName);
        teacher.setUserName(userName);
        teacher.setSubjectId(subjectId);
        teacher.setClassPrice(classPrice);
        teacher.setClassFee(classFee);

        //--2 密码
        String salt = StringTools.getRandomString(32);
        teacher.setUserSalt(salt);

        // 生成密码(123456.oieuroqeuro)
        String password = "123456" + "." +salt;
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("pass:"+md5Password);
        teacher.setUserPass(md5Password);

        tbTeacherMapper.insert(teacher);
        if(teacher.getId() != null) {
            teacher.setUserPass("");
            teacher.setUserSalt("");
            resultMap.put("teacher", teacher);

            result.setResult(resultMap);
            return result;
        }

        result.setSuccess(false);
        result.setCode(-1);
        result.setMessage("教师添加失败");
        return result;
    }

    @Override
    public ResponseResult delTeacherUser(Integer teacherId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断用户是否存在
        TbTeacher teacher = tbTeacherMapper.selectById(teacherId);
        if(teacher == null) {
            result.setFailMessage("教师不存在");
            return result;
        }

        if(!teacher.getUserStatus().equals(0)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("教师已删除");
            return result;
        }

        //--2 设置删除标志
        teacher.setUserStatus(1);
        tbTeacherMapper.updateById(teacher);

        resultMap.put("teacher", teacher);
        result.setResult(resultMap);

        return result;
    }

    @Override
    public ResponseResult setTeacherPass(Integer teacherId, String passWord) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断用户是否存在
        TbTeacher teacher = tbTeacherMapper.selectById(teacherId);
        if(teacher == null) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("教师不存在");
            return result;
        }

        if(!teacher.getUserStatus().equals(0)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("教师员已删除");
            return result;
        }

        //--2 修改密码
        // 生成密码(123456.oieuroqeuro)
        String password = passWord + "." + teacher.getUserSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("pass:"+md5Password);
        teacher.setUserPass(md5Password);

        tbTeacherMapper.updateById(teacher);

        resultMap.put("teacher", teacher);
        result.setResult(resultMap);

        return result;
    }

    @Override
    public ResponseResult setTeacherInfo(Integer teacherId, String nickName, Integer subjectId, Long classPrice, Long classFee) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //-- 检查用户是否存在
        TbTeacher teacher = tbTeacherMapper.selectById(teacherId);
        if(teacher == null) {
            result.setFailMessage("教师不存在");
            return result;
        }

        //--1 用户名
        teacher = new TbTeacher();
        teacher.setId(teacherId);
        teacher.setNickName(nickName);
        teacher.setSubjectId(subjectId);
        teacher.setClassPrice(classPrice);
        teacher.setClassFee(classFee);

        tbTeacherMapper.updateById(teacher);

        resultMap.put("teacher", teacher);
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult doTeacherLogin(String userName, String passWord) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 查询用户
        TbTeacher teacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>()
                .eq("user_name", userName)
                .eq("user_status", 0)
                .last("limit 1"));
        if(teacher == null) {
            result.setFailMessage("教师不存在");
            return result;
        }

        //--2 判断密码
        String password = passWord + "." + teacher.getUserSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!teacher.getUserPass().equals(md5Password)) {
            result.setFailMessage("教师密码不正确");
            return result;
        }

        //--3 生成token
        String token = JwtTokenUtils.makeToken(teacher.getId(), teacher.getUserName(), "teacher");
        resultMap.put("teacher", teacher);
        resultMap.put("token", token);

        result.setResult(resultMap);

        //--4 单点登录
        String key = "teacher_token_" + teacher.getId();
        redisTemplate.opsForValue().set(key, token, 1, TimeUnit.DAYS);

        return result;
    }

    @Override
    public ResponseResult getTeacherInfo(Integer teacherId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 查询科目是否存在
        TbTeacher teacher = tbTeacherMapper.selectOne(
                new QueryWrapper<TbTeacher>()
                .eq("id", teacherId)
                .eq("user_status", 0)
                .last("limit 1")
        );
        if(teacher == null) {
            result.setFailMessage("教师不存在");
            return result;
        }

        resultMap.put("teacher", teacher);
        result.setResult(resultMap);

        return result;
    }

    @Override
    public ResponseResult getTeacherByPage(Integer pageCurrent, Integer pageSize) {

        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

//        Page<TbTeacher> page = new Page<>(pageCurrent, pageSize);
//        QueryWrapper<TbTeacher> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select(TbTeacher.class, i -> !i.getColumn().equals("user_pass") && !i.getColumn().equals("user_salt"));
//        queryWrapper.orderByAsc("id");
//        IPage<TbTeacher> teachers = tbTeacherMapper.selectPage(page, queryWrapper);

        Page<TbTeacher> page = new Page<>(pageCurrent, pageSize);
        IPage<TbTeacher> teachers = tbTeacherMapper.getTeacher4Page(page);

        resultMap.put("teachers", teachers);
        result.setResult(resultMap);

        return result;
    }
}
